<script setup lang="ts">
  import { Ref, ref, watch } from 'vue';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import { LocaleData } from '@/api/locale/types';
  import { createLocale, editLocale } from '@/api/locale';

  const dialogVisiable = ref(false);
  const addForm: Ref<LocaleData> = ref({
    key: '',
    chineseMessage: '',
    englishMessage: '',
  });
  const formRules: FormInstance['rules'] = {
    key: [{ required: true, message: '国际化键名不能为空' }],
    chineseMessage: [{ required: true, message: '中文文本不能为空' }],
    englishMessage: [{ required: true, message: '英文文本不能为空' }],
  };
  const emit = defineEmits(['saveSuccess']);
  const formRef = ref();
  const saveId = ref();
  // 打开
  const handleOpen = () => {
    dialogVisiable.value = true;
  };
  // 保存
  const handleSave = async () => {
    try {
      const isInvalid = await formRef.value?.validate();
      if (isInvalid) return false;
      // 保存和编辑
      if (saveId.value) {
        await editLocale(addForm.value);
      } else {
        await createLocale(addForm.value);
      }
      dialogVisiable.value = false;
      Message.success('保存成功');
      emit('saveSuccess');
      return true;
    } catch (error) {
      return false;
    }
  };
  // 编辑
  const handleEdit = async ({ key, chineseMessage, englishMessage }: any) => {
    saveId.value = key;
    addForm.value = {
      key,
      chineseMessage,
      englishMessage,
    };
    dialogVisiable.value = true;
  };
  // 点击关闭-取消按钮后触发
  const handleCancel = () => {
    dialogVisiable.value = false;
  };
  // 对话框关闭后触发
  const handleClose = () => {
    formRef.value.resetFields();
    saveId.value = undefined;
  };

  // 暴露方法
  defineExpose({
    handleOpen,
    handleEdit,
  });
</script>

<template>
  <a-modal
    :visible="dialogVisiable"
    title-align="start"
    :ok-text="$t('modal.operation.save')"
    :cancel-text="$t('modal.operation.cancel')"
    unmount-on-close
    @before-ok="handleSave"
    @close="handleClose"
    @cancel="handleCancel"
  >
    <template #title
      >{{
        saveId
          ? $t('searchTable.operation.edit')
          : $t('searchTable.operation.create')
      }}
    </template>
    <a-form ref="formRef" :rules="formRules" :model="addForm" auto-label-width>
      <a-form-item field="key" label="国际化键名">
        <a-input
          v-model="addForm.key"
          allow-clear
          placeholder="请输入国际化键名"
          :readonly="!!saveId"
        ></a-input>
      </a-form-item>
      <a-form-item field="chineseMessage" label="中文文本">
        <a-input
          v-model="addForm.chineseMessage"
          placeholder="请输入中文文本"
          allow-clear
        />
      </a-form-item>
      <a-form-item field="englishMessage" label="英文文本">
        <a-input
          v-model="addForm.englishMessage"
          placeholder="请输入英文文本"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less"></style>
